﻿var eventID;
var modeJsonObj = [];
var bedNo;
var visitID;
var tempPatientID = "";
var tempPatientName = "";
var firsLoad = true;
var zjwhID = "";
$(function () {
    eventID = $("#hdnEventID").val();

    var eventTypeData;
    $("#eventTypeID").ligerComboBox({
        width: 140,
        cancelable: false,
        url: "/AdverseEvent/EditAdverseEvent/GetAdverseEventTypeList?ram" + Math.random(),
        valueField: "ID",
        textField: "Name",
        valueFieldID: 'hdnEventTypeID',
        onSelected: function (value, text) {
            displayMode();
            displayReason();
            if (text == "压力性损伤") {
                $("#liYcFanKui").show();
                $("#divYcFanKui").show();
                $("#divIsTransfer").show();
            }
            else {
                $("#liYcFanKui").hide();
                $("#divYcFanKui").hide();
                $("#divIsTransfer").hide();
            }
            position();
            for (var i = 0; i < eventTypeData.length; i++) {
                if (eventTypeData[i].ID == value) {
                    $("#eventName").text(eventTypeData[i].Name);
                    if (eventTypeData[i].Remark != null && eventTypeData[i].Remark != "") {
                        $("#eventRemark").text(eventTypeData[i].Remark);
                        $("#trEventRemark").show();
                    }
                    else {
                        $("#trEventRemark").hide();
                    }
                }
            }
        },
        onSuccess: function (data) {
            eventTypeData = data;
            if (eventID == 0) {
                $("#eventTypeID").ligerComboBox().setValue(6);
            }
        }
    });

    $("#areaID").ligerComboBox({
        cancelable: false,
        width: 140,
        url: "/AdverseEvent/EditAdverseEvent/GetAllUnits?ram" + Math.random(),
        valueField: "DepartmentCode",
        textField: "DepartmentName",
        valueFieldID: 'hdnAreaID',
        onSelected: function (value) {
            getPatientList();
            $.ajax({
                url: "/AdverseEvent/EditAdverseEvent/GetNurseList?ram" + Math.random(),
                type: "post",
                data: { departmentCode: value },
                success: function (r) {
                    var d = $.parseJSON(r);
                    $("#nurseID").ligerComboBox().setData(d);
                    if (eventID == 0) {
                        $("#nurseID").ligerComboBox().setValue($("#hdnPersonnelId").val());
                    }
                }
            });
        },
        onSuccess: function (data) {
            if (eventID == 0) {
                $("#areaID").ligerComboBox().setValue($("#hdnCurrDepCode").val());
            }
        }
    });

    $("#patientID").ligerComboBox({
        cancelable: false,
        autocomplete: true,
        keySupport: true,
        width: 140,
        valueField: "PATIENT_ID",
        textField: "PATIENT_NAME",
        valueFieldID: 'hdnPatientID',
        onSelected: function (value) {
            if (tempPatientID == "") {
                var data = $("#patientID").ligerComboBox().data;
                for (var i = 0; i < data.length; i++) {
                    if (data[i].PATIENT_ID == value) {
                        $("#txtPatientID").val(value);
                        $("#txtPatientSex").val(data[i].SEX);
                        if (data[i].SEX == 1 || data[i].SEX == 2) {
                            if (data[i].SEX == 1)
                                $("#txtPatientSex").val("男");
                            else
                                $("#txtPatientSex").val("女");
                        }
                        if (!isNaN(data[i].AGE)) {
                            $("#txtPatientAge").val(data[i].AGE);
                            $("#divAge").show();
                            $("#divAgeStr").hide();
                        }
                        else {
                            $("#txtPatientAgeStr").val(data[i].AGE);
                            $("#divAge").hide();
                            $("#divAgeStr").show();
                        }
                        $("#txtPatientInTime").val(data[i].IN_DATE);
                        $("#patientNursingGrade").ligerComboBox().setValue($("#patientNursingGrade").ligerComboBox().findValueByText(data[i].NURSING));
                        $("#txtPatientDiagnosis").val(data[i].DIAGNOSE);
                        bedNo = data[i].BED_NO;
                        visitID = data[i].VISIT_ID;
                        break;
                    }
                }
            }
            else {
                if ($("#patientID").ligerComboBox().getText() == "") {
                    $("#patientID").ligerComboBox().insertItem({ PATIENT_ID: tempPatientID, PATIENT_NAME: " " + tempPatientName }, 0);
                    $("#patientID").ligerComboBox().setValue(tempPatientID);
                    $("#patientID").ligerComboBox().setDisabled(false);
                }
            }
        }
    });

    $("#patientNursingGrade").ligerComboBox({
        cancelable: false,
        width: 140,
        data: [
            { text: '全部', id: 'c001' },
            { text: '新入', id: 'c002' },
            { text: '一般', id: 'c003' },
            { text: '病危', id: 'c004' },
            { text: '病重', id: 'c005' },
            { text: '特级护理', id: 'c006' },
            { text: 'Ⅰ级护理', id: 'c007' },
            { text: 'Ⅱ级护理', id: 'c008' },
            { text: '重症监护', id: 'c009' },
            { text: '今日手术', id: 'c0010' },
            { text: '术后1天', id: 'c0011' },
            { text: '术后2天', id: 'c0012' },
            { text: '术后3天', id: 'c0013' },
            { text: '明日出院', id: 'c0014' }
        ],
        valueField: "id",
        textField: "text",
        valueFieldID: 'hdnPatientNursingGrade',
        onSelected: function (value) {
        }
    });

    bindNurseRank();

    $("#nurseID").ligerComboBox({
        isMultiSelect: true,
        isShowCheckBox: true,
        cancelable: false,
        width: 440,
        valueField: "UserId",
        textField: "UserName",
        valueFieldID: 'hdnNurseID',
        onSelected: function (value) {
            initNurseList();
            position();
            $("#nurseID").ligerComboBox({
                onChangeValue: function (value) {
                    var values = $("#hdnNurseID").val().split(';');
                    var texts = value.split(';');
                    for (var i = 0; i < values.length; i++) {
                        var nurseTr = $("#nurseItem_" + values[i]);
                        if (nurseTr.length == 0 && values != "") {
                            var tr = $("#nurseItem").clone();
                            tr.attr('id', 'nurseItem_' + values[i]);
                            tr.find("#nurseID").val(values[i]).attr('id', 'nurseID_' + values[i]);
                            tr.find("#nurseName").text(texts[i]).attr('id', 'nurseName_' + values[i]);
                            tr.find("#nurseAge").attr('id', 'nurseAge_' + values[i]);
                            tr.find("#nurseRank").attr('id', 'nurseRank_' + values[i]);
                            tr.find("#nurseWorkAge").attr('id', 'nurseWorkAge_' + values[i]);
                            tr.find("#nurseDepartAge").attr('id', 'nurseDepartAge_' + values[i]);
                            $("#nurseItem").after($(tr));
                            tr.show();
                        }
                    }
                    var nurselist = $("tr[id^='nurseItem_']");
                    nurselist.each(function (val, index) {
                        var id = $(this).attr("id").replace('nurseItem_', '');
                        if ($.inArray(id, values) == -1) {
                            $(this).remove();
                        }
                    });
                    if ($("tr[id^='nurseItem_']").length == 0) {
                        $("#nurseListTr").hide()
                    }
                    else {
                        $("#nurseListTr").show()
                    }
                    position();
                }
            });

            if (firsLoad) {
                ///回页面顶部
                document.body.scrollTop = document.documentElement.scrollTop = 0;
                $(".lift").children().eq(0).addClass("current");
                $("#eventTypeID").focus().blur();
                $("#pageloading").hide();
                firsLoad = false;
            }
        }
    });

    $("#txtOccurrTime,#txtPatientInTime,#txtTransferTime,#txtOutpatientTime").ligerDateEditor({
        showTime: true,
        format: "yyyy-MM-dd hh:mm:ss",
        width: 140,
        cancelable: false
    });

    $("input[name=eventGrade]").click(function (item) {
        $(".divEventGrade").show();
        $("[id^=divEventGrade]").hide();
        $("#divEventGrade" + $(this).val()).show();
        $("[id^=fontEventGrade]").hide();
        $("#fontEventGrade" + $(this).val()).show();
        position();
    });

    $("input[name=eventGradeSubLevel]").click(function (item) {
        $("[id^=fontEventGradeSubLevel]").hide();
        $("#fontEventGradeSubLevel" + $(this).val()).show();
        position();
    });

    $("input[id^=isOutpatient]").click(function (item) {
        if ($(this).val() == 0) {
            $("#divPatientID").show();
            $(".inpatientInfo").show();
            $("#divDischargedPatients").show();
            $("#divPatientName").hide();
            $(".outpatientInfo").hide();
            var data = $("#patientID").ligerComboBox().data;
            if (data.length > 0) {
                $("#patientID").ligerComboBox().setValue(data[0].PATIENT_ID);
            }
        }
        else {
            $("#divPatientID").hide();
            $(".inpatientInfo").hide();
            $("#divDischargedPatients").hide();
            $("#divPatientName").show();
            $(".outpatientInfo").show();
            $("#txtPatientSex").val('');
            $("#txtPatientAge").val('');
            $("#txtPatientAgeStr").val('');
            $("#txtPatientAgeMonth").val('');
            $("#txtPatientAgeWeek").val('');
            $("#txtPatientAgeDay").val('');
        }
        position();
    });

    $("#isDischargedPatients").click(function () {
        $("#patientID").ligerComboBox().setDisabled();
        getPatientList();
    });

    $("#btnBack").click(function () {
        if ($("#hdnPageType").val() == 0) {
            location.href = "/AdverseEvent/AdverseEventList";
        }
        else {
            location.href = "/AdverseEvent/AdverseEventReview";
        }
    });

    $('#btnYG').click(function () {
        location.href = "/AdverseEvent/EditAdverseEvent/PaintYG?eventID=" + eventID;
    });

    $("#btnReport").click(function () {
        location.href = "/AdverseEvent/EditAdverseEvent/Report?eventID=" + eventID + "&flag_Yc=" + ($("#divYcFanKui").is(':visible') ? 1 : 0);
    });

    $(".trFanKui").dblclick(function () {
        ycFanKui();
    });

    bindAdverseEvent();

    getYcFanKui();
});

function getPatientList() {
    $.ajax({
        url: "/AdverseEvent/EditAdverseEvent/GetPatientList?ram" + Math.random(),
        type: "post",
        data: { departmentCode: $("#hdnAreaID").val(), isDischargedPatients: ($("#isDischargedPatients").is(':checked') ? 1 : 0) },
        success: function (r) {
            var d = $.parseJSON(r);
            for (var i = 0; i < d.length; i++) {
                d[i].PATIENT_NAME = d[i].BED_NO + " " + d[i].PATIENT_NAME + " " + d[i].PATIENT_ID;
            }
            $("#patientID").ligerComboBox({ data: d, dataList: d }).setEnabled();
            $("#patientID").ligerComboBox().updateStyle();
            if (eventID == 0) {
                if (d.length > 0)
                    $("#patientID").ligerComboBox().setValue(d[0].PATIENT_ID);
            }
            else {
                if (tempPatientID != "") {
                    $("#patientID").ligerComboBox().setValue(tempPatientID);
                    tempPatientID = "";
                }
            }
        }
    });
}

function bindAdverseEvent() {
    if (eventID != 0) {
        $.ajax({
            url: "/AdverseEvent/EditAdverseEvent/GetAdverseEvent?ram" + Math.random(),
            type: "post",
            data: { id: eventID },
            success: function (r) {
                var event = $.parseJSON(r);
                if (event.Status != $("#hdnStatus").val()) {
                    $("#pageloading").hide();
                    $.ligerDialog.error("事件状态已改变！");
                    setTimeout(function () { $("#btnBack").click(); }, 1000);
                    return;
                }
                $("#eventTypeID").ligerComboBox().setValue(event.EventTypeID);
                $("#areaID").ligerComboBox().setValue(event.OccurrDepartID);
                var _PatientID = event.PatientID;
                if (_PatientID != "" && _PatientID != null)
                    tempPatientID = event.PatientID.replace(/\s+/g, "");
                tempPatientName = event.PatientName;
                $('input:radio[name="isOutpatient"][value=' + event.IsOutpatient + ']').attr('checked', 'true').click();
                $("#txtPatientID").val(event.PatientID);
                $("#txtPatientSex").val(event.PatientSex);
                $("#txtPatientAge").val(event.PatientAge == 0 ? "" : event.PatientAge);
                $("#txtPatientAgeMonth").val(event.PatientAgeMonth == 0 ? "" : event.PatientAgeMonth);
                $("#txtPatientAgeWeek").val(event.PatientAgeWeek == 0 ? "" : event.PatientAgeWeek);
                $("#txtPatientAgeDay").val(event.PatientAgeDay == 0 ? "" : event.PatientAgeDay);
                $("#txtPatientAgeStr").val(event.PatientAgeStr);
                if (!IsEmpty(event.PatientAgeStr)) {
                    $("#divAge").hide();
                    $("#divAgeStr").show();
                }
                else {
                    $("#divAge").show();
                    $("#divAgeStr").hide();
                }
                $("#txtPatientInTime").val(event.PatientInTime);
                bedNo = event.PatientBedNo;
                visitID = event.PatientVisitID;
                $("#transferDepartCode").val(event.TransferDepartCode);
                $('input:radio[name="isTransfer"][value=' + event.IsTransfer + ']').attr('checked', 'true').click();
                $("#txtTransferTime").val(event.TransferTime);
                $("#txtOccurrTime").val(event.OccurrTime);
                if (event.ID > 0) {
                    $("#trCreateTime").show();
                    $("#txtCreateTime").val(event.CreateTime);
                }
                $("#patientNursingGrade").ligerComboBox().setValue(event.PatientNursingGrade);
                $('input:radio[name="patientIsEscort"][value=' + event.PatientIsEscort + ']').attr('checked', 'true').click();
                if (event.PatientIsEscort == 1 && (event.PatientEscortValue != null && event.PatientEscortValue != "")) {
                    var escortValue = event.PatientEscortValue.split('#');
                    for (var i = 0; i < escortValue.length; i++) {
                        $('[id^="patientIsEscort2_"][value=' + escortValue[i] + ']').attr('checked', 'true');
                    }
                }
                $("#nurseID").ligerComboBox().setValue(event.NurseID.replace(/,/g, ";"));
                var nurseWorkTimes = event.NurseWorkTimes.split('~');
                if (nurseWorkTimes.length > 0) $("#txtWorkStartTime").val(nurseWorkTimes[0]);
                if (nurseWorkTimes.length > 1) $("#txtWorkEndTime").val(nurseWorkTimes[1]);
                $("#txtPatientDiagnosis").val(event.PatientDiagnosis);
                $('input:radio[name="eventGrade"][value=' + event.EventGrade + ']').attr('checked', 'true').click();
                $('input:radio[name="eventGradeSubLevel"][value=' + event.EventGradeSubLevel + ']').attr('checked', 'true').click();
                $("#txtPatientName").val(event.PatientName);
                $("#txtOutpatientTime").val(event.OutpatientTime);
                $("#txtOutpatientId").val(event.OutpatientId);
                $("#txtEventCourse").val(event.EventCourse);
                $("#txtMeasures").val(event.Measures);
                $("#txtEvaluation").val(event.Evaluation);
                $("#txtYuHou").val(event.YuHou);
                $("#txtZhuanGui").val(event.ZhuanGui);
                $("#btnYG").show();
                $("#btnReport").show();

                if ($("#hdnPageType").val() == 0) {
                    if (event.Status == 0 || event.Status == 3) {
                        $("#btn1").val("保存").show().click(function () { save(event.Status) });
                        $("#btn2").val("上报").show().click(function () { save(1) });
                    }
                }
                else {
                    var detailsViewBtns = JSON.parse($("#hdnDetailsViewBtns").val().replace(/([^\\])'/g, '$1\"'));
                    for (var i = 0; i < detailsViewBtns.length; i++) {
                        var detailsViewBtn = detailsViewBtns[i];
                        var run = detailsViewBtn.Function + '(' + detailsViewBtn.Parameter + ')';
                        $("#btn" + (i + 1)).val(detailsViewBtn.BtnName).attr("run", run).show().click(function () { eval($(this).attr("run")) });
                    }
                }
            }
        });
    }
    else {
        $("#btn1").val("保存").show().click(function () { save(0) });
        $("#btn2").val("上报").show().click(function () { save(1) });
    }
}

function getYcFanKui() {
    $.ajax({
        url: "/AdverseEvent/EditPressureSoreEvent/GetYcFanKui?ram" + Math.random(),
        type: "post",
        data: { eventID: eventID },
        success: function (r) {
            $("#hdnYcFanKuiJson").val(r);
        }
    });
}

function displayMode() {
    $("[id^=tr_mode_]").each(function () {
        $(this).remove();
    })

    modeJsonObj = [];
    var typeID = $("#hdnEventTypeID").val();

    $.ajax({
        url: "/AdverseEvent/EditAdverseEvent/GetAdverseEventModeList?ram" + Math.random(),
        type: "post",
        async: false,
        data: { typeID: typeID, eventID: eventID },
        success: function (r) {
            modeJsonObj = $.parseJSON(r);
        }
    });

    for (var i = modeJsonObj.length - 1; i >= 0 ; i--) {
        var id = modeJsonObj[i].ModeID;
        var strTr = '<tr id="{0}" style="height: 35px;"><td style="width: 100px; text-align: right;vertical-align: text-top; padding-top: 8px;">{1}：</td><td style="line-height:35px;">{2}</td></tr>';
        strTr = strTr.replace("{0}", "tr_mode_" + id);
        if (modeJsonObj[i].ModeName.length > 10) {
            var modeName = modeJsonObj[i].ModeName.substring(0, 7) + "&nbsp;&nbsp;</br>";
            modeName += modeJsonObj[i].ModeName.substring(7, modeJsonObj[i].ModeName.length);
            strTr = strTr.replace("{1}", modeName);
        }
        else {
            strTr = strTr.replace("{1}", modeJsonObj[i].ModeName);
        }

        var isyclx = false;
        if (modeJsonObj[i].ModeName == "压伤类型") {
            isyclx = true;
        }

        if (modeJsonObj[i].ModeName == "至今未回") {
            zjwhID = "tr_mode_" + modeJsonObj[i + 1].ModeID;
        }
        var isDate = false;
        var dateId = "";
        switch (modeJsonObj[i].InputType) {
            case 0:
                var temp = "";
                var values = [];
                if (modeJsonObj[i].Value != "" && modeJsonObj[i].Value != null) values = modeJsonObj[i].Value.split('#');
                var options = modeJsonObj[i].Options.split('#');
                for (var ii = 0; ii < options.length; ii++) {
                    var value = values[ii] == undefined ? "" : values[ii].split("$0%")[0];
                    var option = options[ii].split("$0%")[0];
                    temp += "<div style=\"float:left; margin-right:5px;\"><label for=\"mode_" + id + "_" + ii + "\" style=\"display:" + ((isyclx && (ii == 0 || ii == 2)) ? "none;" : "") + "\">";
                    temp += "<input type=\"radio\" id=\"mode_" + id + "_" + ii + "\" name=\"mode_" + id + "\"" + (value == "1" ? "checked" : "") + " hdnValue=\"" + values[ii] + "\" hdnOption=\"" + options[ii] + "\"/><font>" + option + "</font></label></div>";
                    temp += "<div id=\"divDetailsMode_" + id + "_" + ii + "\" style=\"float:left; margin-right:5px;\"></div>";
                }
                strTr = strTr.replace("{2}", temp);
                break;
            case 1:
                var temp = "";
                var values = [];
                if (modeJsonObj[i].Value != "" && modeJsonObj[i].Value != null) values = modeJsonObj[i].Value.split('#');
                var options = modeJsonObj[i].Options.split('#');
                for (var ii = 0; ii < options.length; ii++) {
                    var value = values[ii] == undefined ? "" : values[ii].split("$0%")[0];
                    var option = options[ii].split("$0%")[0];
                    temp += "<div style=\"float:left; margin-right:5px;\"><label for=\"mode_" + id + "_" + ii + "\" style=\"display:" + ((isyclx && (ii == 0 || ii == 2)) ? "none;" : "") + "\">";
                    temp += "<input type=\"checkbox\" id=\"mode_" + id + "_" + ii + "\" name=\"mode_" + id + "\"" + (value == "1" ? "checked" : "") + " hdnValue=\"" + values[ii] + "\" hdnOption=\"" + options[ii] + "\"/><font>" + option + "</font></label></div>";
                    temp += "<div id=\"divDetailsMode_" + id + "_" + ii + "\" style=\"float:left; margin-right:5px;\"></div>";
                }
                strTr = strTr.replace("{2}", temp);
                break;
            case 2:
                var temp = "<input type=\"text\" id=\"mode_" + id + "\" value=\"" + (modeJsonObj[i].Value == null ? "" : modeJsonObj[i].Value) + "\"  style=\"width: 440px;\" class=\"l-text\" maxlength=\"500\"/>";
                strTr = strTr.replace("{2}", temp);
                break;
            case 3:
                isDate = true;
                dateId = "mode_" + id;
                var temp = "<input type=\"text\" id=\"mode_" + id + "\" value=\"" + (modeJsonObj[i].Value == null ? "" : modeJsonObj[i].Value) + "\"/>";
                strTr = strTr.replace("{2}", temp);
                break;

        }
        $("#insertMode").after($(strTr));
        if (isDate) {
            setDateEditor(dateId);
        }
    }
    displayDetailsMode();
    $('input[name^=mode_]:checked').click().click();
    setYcBraden();
    initYcFsbw();
}

function displayReason() {
    var jsonObj = [];
    var typeID = $("#hdnEventTypeID").val();

    $.ajax({
        url: "/AdverseEvent/EditAdverseEvent/GetAdverseEventReasonList?ram" + Math.random(),
        type: "post",
        async: false,
        data: { typeID: typeID, eventID: eventID },
        success: function (r) {
            jsonObj = $.parseJSON(r);
        }
    });
    $("#reasonList tr").empty();
    for (var i = 0; i < jsonObj.length; i++) {
        var strTr = "<tr><td style='width: 100px;'>{0}</td><td><font style=\"color:#00f\">{1}</font></td><td style=\"border-right:0px;\">{2}</td><td style=\"border-left:0px;\">{3}</td></tr>";

        if ((jsonObj[i].Level == 1 || jsonObj[i].Level == 2) && jsonObj[i].Cnt > 0) {
            continue;
        }
        var path = jsonObj[i].Path.split('#');
        var reasons = jsonObj[i].Reason.split('#');
        if (reasons.length >= 1) {
            if ($("#reasons_" + path[0]).length == 0) {
                strTr = strTr.replace("{0}", "<font style=\"display:none;\">" + path[0] + "</font><input type=\"checkbox\"  id=\"reasons_" + path[0] + "\" value=\"" + path[0] + "\" Level=\"1\" style=\"display:none;\"/>" + reasons[0]);
            }
            else {
                strTr = strTr.replace("{0}", "<font style=\"display:none;\">" + path[0] + "</font>" + reasons[0]);
            }
            if (reasons.length == 1) {
                strTr = strTr.replace("{1}", "");
                strTr = strTr.replace("{2}", "");
                strTr = strTr.replace("{3}", "");
            }
        }
        if (reasons.length >= 2) {
            if ($("#reasons_" + path[1]).length == 0) {
                strTr = strTr.replace("{1}", "<font style=\"display:none;\">" + path[1] + "</font><label for=\"reasons_" + path[1] + "\"><input type=\"checkbox\" id=\"reasons_" + path[1] + "\" value=\"" + path[1] + "\"  parentID=\"" + path[0] + "\" Level=\"2\"" + (jsonObj[i].IsChecked > 0 ? "Checked" : "") + " reason=\"" + reasons[1] + "\"/>" + reasons[1] + "</label>" + (reasons[1] == "其他" ? "&nbsp;<input type=\"text\" class=\"l-text\" style=\"width:100px;display:none;\" maxlength=\"20\" value=\"" + (jsonObj[i].OtherReason == null ? "" : jsonObj[i].OtherReason) + "\" />" : ""));
            }
            else {
                strTr = strTr.replace("{1}", "<font style=\"display:none;\">" + path[1] + "</font>" + reasons[1]);
            }
            if (reasons.length == 2) {
                strTr = strTr.replace("{2}", "");
                strTr = strTr.replace("{3}", "");
            }
        }
        if (reasons.length == 3) {
            strTr = strTr.replace("{2}", "<label for=\"reasons_" + jsonObj[i].ReasonID + "\"><input type=\"checkbox\" id=\"reasons_" + jsonObj[i].ReasonID + "\" value=\"" + jsonObj[i].ReasonID + "\"  parentID=\"" + jsonObj[i].ParentId + "\" Level=\"3\" " + (jsonObj[i].IsChecked > 0 ? "Checked" : "") + " reason=\"" + reasons[2] + "\"/>" + reasons[2] + "</label>" + (reasons[2] == "其他" || reasons[2] == "其它" ? "&nbsp;<input type=\"text\" class=\"l-text\" style=\"width:100px;display:none;\" maxlength=\"20\" value=\"" + (jsonObj[i].OtherReason == null ? "" : jsonObj[i].OtherReason) + "\" />" : ""));
            if (jsonObj[i].ParentId == jsonObj[i + 1].ParentId) {
                i++;
                reasons = jsonObj[i].Reason.split('#');
                strTr = strTr.replace("{3}", "<label for=\"reasons_" + jsonObj[i].ReasonID + "\"><input type=\"checkbox\" id=\"reasons_" + jsonObj[i].ReasonID + "\" value=\"" + jsonObj[i].ReasonID + "\" parentID=\"" + jsonObj[i].ParentId + "\" Level=\"3\" " + (jsonObj[i].IsChecked > 0 ? "Checked" : "") + " reason=\"" + reasons[2] + "\"/>" + reasons[2] + "</label>" + (reasons[2] == "其他" || reasons[2] == "其它" ? "&nbsp;<input type=\"text\" class=\"l-text\" style=\"width:100px;display:none;\" maxlength=\"20\" value=\"" + (jsonObj[i].OtherReason == null ? "" : jsonObj[i].OtherReason) + "\" />" : ""));
            }
            else {
                strTr = strTr.replace("{3}", "");
            }
        }
        $("#reasonList").append($(strTr));
    }

    tableRowspan("#reasonList", 1);
    tableRowspan("#reasonList", 2);


    $("input[Level='2']").click(function (value) {
        var id = $(this).val();
        var chbox = $(this);

        if ($(this).attr("reason") == "其他" || $(this).attr("reason") == "其它") {
            if (chbox.prop("checked"))
                $(this).parent().next().show();
            else
                $(this).parent().next().hide();
        }

        $("input[parentID='" + id + "']").each(function () {
            $(this).prop("checked", chbox.prop("checked"));
            if ($(this).attr("reason") == "其他" || $(this).attr("reason") == "其它") {
                if ($(this).prop("checked"))
                    $(this).parent().next().show();
                else
                    $(this).parent().next().hide();
            }
        });

        id = $(this).attr("parentID");
        if ($("input[parentID='" + id + "']:checked").length == 0) {
            $("input[value='" + id + "']").prop("checked", false);
        }
        else {
            $("input[value='" + id + "']").prop("checked", true);
        }
    });

    $("input[Level='3']").click(function (value) {
        var id = $(this).attr("parentID");

        if ($(this).attr("reason") == "其他" || $(this).attr("reason") == "其它") {
            if ($(this).prop("checked"))
                $(this).parent().next().show();
            else
                $(this).parent().next().hide();
        }

        if ($("input[parentID='" + id + "']:checked").length == 0) {
            $("input[value='" + id + "']").prop("checked", false);
        }
        else {
            $("input[value='" + id + "']").prop("checked", true);
        }

        id = $("input[value='" + id + "']").attr("parentID");
        if ($("input[parentID='" + id + "']:checked").length == 0) {
            $("input[value='" + id + "']").prop("checked", false);
        }
        else {
            $("input[value='" + id + "']").prop("checked", true);
        }
    });
    if (eventID > 0) {
        $("#reasonList").find('input[type="checkbox"][level="3"]:checked').each(function (i, eleDom) {
            $(this).click().click();//选中一二级的根因
        });
        $("#reasonList").find('input[type="checkbox"][level="2"]:checked').each(function (i, eleDom) {
            $("input[value='" + $(this).attr("parentID") + "']").prop("checked", true);//选中一级的根因
        });
        $("#reasonList").find('input[type="checkbox"][reason = "其他"]:checked').each(function (i, eleDom) {
            $(this).click().click();//显示其他项的文本框
        });
        $("#reasonList").find('input[type="checkbox"][reason = "其它"]:checked').each(function (i, eleDom) {
            $(this).click().click();//显示其它项的文本框
        });
    }
    position();
}

function bindNurseRank() {
    $.ajax({
        url: "/AdverseEvent/EditAdverseEvent/GetPositionlist?ram" + Math.random(),
        type: "post",
        async: false,
        data: {},
        success: function (r) {
            var jsonObj = $.parseJSON(r);
            for (var i = 0; i < jsonObj.length; i++) {
                jsonObj
                $("#nurseRank").append("<option value=\"" + jsonObj[i].PositionCode + "\">" + jsonObj[i].PositionTitle + "</option>");
            }
        }
    });
}

function initNurseList() {
    var jsonObj = [];
    if (eventID > 0) {
        $.ajax({
            url: "/AdverseEvent/EditAdverseEvent/GetAdverseEventNurse?ram" + Math.random(),
            type: "post",
            async: false,
            data: { eventID: eventID },
            success: function (r) {
                jsonObj = $.parseJSON(r);
            }
        });
    }
    else {
        if ($("#nurseID_" + $("#hdnPersonnelId").val()).length == 0) {
            jsonObj.push({
                NurseID: $("#hdnPersonnelId").val(), NurseName: $("#hdnUserName").val()
            });
        }
    }

    for (var i = jsonObj.length - 1; i >= 0 ; i--) {
        var tr = $("#nurseItem").clone();
        tr.attr('id', 'nurseItem_' + jsonObj[i].NurseID);
        tr.find("#nurseID").val(jsonObj[i].NurseID).attr('id', 'nurseID_' + jsonObj[i].NurseID);
        tr.find("#nurseName").text(jsonObj[i].NurseName).attr('id', 'nurseName_' + jsonObj[i].NurseID);
        tr.find("#nurseAge").val(jsonObj[i].NurseAge).attr('id', 'nurseAge_' + jsonObj[i].NurseID);
        tr.find("#nurseRank").val(jsonObj[i].NurseRank).attr('id', 'nurseRank_' + jsonObj[i].NurseID);
        tr.find("#nurseWorkAge").val(jsonObj[i].NurseWorkAge).attr('id', 'nurseWorkAge_' + jsonObj[i].NurseID);
        tr.find("#nurseDepartAge").val(jsonObj[i].NurseDepartAge).attr('id', 'nurseDepartAge_' + jsonObj[i].NurseID);
        $("#nurseItem").after($(tr));
        tr.show();
    }
    if ($("tr[id^='nurseItem_']").length == 0) {
        $("#nurseListTr").hide()
    }
    else {
        $("#nurseListTr").show()
    }
}

function position() {
    LiftEffect({
        "control1": ".lift-nav",
        "control2": ".lift",
        "target": [".t1", ".t2", ".t3", ".t4", ".t5"],
        "current": "current"
    });
}

function setDateEditor(id) {
    $("#" + id).ligerDateEditor({
        showTime: true,
        format: "yyyy-MM-dd hh:mm:ss",
        width: 140,
        cancelable: false,
        initValue: IsEmpty($("#" + id).val()) ? "" : $("#" + id).val()
    });
}

function displayDetailsMode() {
    $("input[name^=mode_]").click(function (item) {
        var eventTypeName = $("#eventTypeID").ligerComboBox().getText();
        if (eventTypeName == "压力性损伤") {
            var td = $(this).parent().parent().parent().prev();
            if (td.text() == "感觉：" || td.text() == "潮湿：" || td.text() == "活动能力：" || td.text() == "移动能力：" || td.text() == "营养：" || td.text() == "摩擦力：") {
                setYcBraden();
                return;
            }
            if (td.text() == "发生部位：") {
                setYcFsbw($(this));
            }
        }
        if (eventTypeName == "病人走失") {
            var td = $(this).parent().parent().parent().prev();
            if (td.text() == "至今未回：") {
                if ($(this).is(":checked")) {
                    $("#" + zjwhID).find("[id^=mode_]").val('');
                    $("#" + zjwhID).hide();
                }
                else {
                    $("#" + zjwhID).show();
                }
            }
        }
        if ($(this).is(":checked")) {
            if ($(this).is(":radio")) {
                $("[id^=" + $(this).attr("name").replace("mode", "divDetailsMode") + "_]").hide();
            }
            $(this).parent().parent().next().show();
            var hdnOption = $(this).attr("hdnOption");
            var hdnValue = $(this).attr("hdnValue");
            if (hdnValue == undefined || hdnValue == "undefined") hdnValue = "";
            if (hdnOption.indexOf("$0%0*") >= 0) {
                $(this).attr("inputType", 0);
                var vlist = hdnValue.split("$0%0*");
                var olist = hdnOption.split("$0%0*");
                if (olist.length > 1) {
                    var values = [];
                    if (vlist[1] != undefined) {
                        values = vlist[1].split('@');
                    }
                    var options = olist[1].split('@');
                    var id = $(this).attr("id");
                    var html = "";
                    for (var i = 0; i < options.length; i++) {
                        var value = values[i];
                        var option = options[i];
                        html += "<div style=\"float:left; margin-right:5px;\"><label for=\"" + id + "_" + i + "\">"
                        html += "<input type=\"radio\" id=\"details_" + id + "_" + i + "\" name=\"" + id + "\"" + (value == "1" ? "checked" : "") + "/>" + option + "</label></div>";
                    }
                    $(this).parent().parent().next().html(html);
                }
            }
            else if (hdnOption.indexOf("$0%1*") >= 0) {
                $(this).attr("inputType", 1);
                var vlist = hdnValue.split("$0%1*");
                var olist = hdnOption.split("$0%1*");
                if (olist.length > 1) {
                    var values = [];
                    if (vlist[1] != undefined) {
                        values = vlist[1].split('@');
                    }
                    var options = olist[1].split('@');
                    var id = $(this).attr("id");
                    var html = "";
                    for (var i = 0; i < options.length; i++) {
                        var value = values[i];
                        var option = options[i];
                        html += "<div style=\"float:left; margin-right:5px;\"><label for=\"" + id + "_" + i + "\">"
                        html += "<input type=\"checkbox\" id=\"details_" + id + "_" + i + "\" name=\"" + id + "\"" + (value == "1" ? "checked" : "") + "/>" + option + "</label></div>";
                    }
                    $(this).parent().parent().next().html(html);
                }
            }
            else if (hdnOption.indexOf("$0%2*") >= 0) {
                $(this).attr("inputType", 2);
                var id = $(this).attr("id");
                var vlist = hdnValue.split("$0%2*");
                var olist = hdnOption.split("$0%2*");
                if (olist.length > 1) {
                    var html = "<input type=\"text\" id=\"details_" + id + "\" value=\"" + (vlist[1] == null ? "" : vlist[1]) + "\"  style=\"width: 150px;\" class=\"l-text\" maxlength=\"500\"/>";
                    $(this).parent().parent().next().html(html);
                }
            }
            else if (hdnOption.indexOf("$0%3*") >= 0) {
                $(this).attr("inputType", 3);
                var id = $(this).attr("id");
                var vlist = hdnValue.split("$0%3*");
                var olist = hdnOption.split("$0%3*");
                if (olist.length > 1) {
                    var html = "<input type=\"text\" id=\"details_" + id + "\" value=\"" + (vlist[1] == null ? "" : vlist[1]) + "\"  style=\"width: 440px;\" class=\"l-text\" maxlength=\"500\"/>";
                    $(this).parent().parent().next().html(html);
                    setDateEditor("details_" + id);
                }
            }
        }
        else {
            $(this).parent().parent().next().hide();
        }
    });
}

function setYcBraden() {
    var value = 0;
    var braden = null;
    var eventTypeName = $("#eventTypeID").ligerComboBox().getText();
    if (eventTypeName != "压力性损伤") return;
    $("#insertMode").nextAll().each(function () {
        var text = $(this).find('td').eq(0).text();
        if (text.indexOf("Braden") >= 0) {
            braden = $(this).find('td').eq(1).children().eq(0);
        }
        if (text == "感觉：" || text == "潮湿：" || text == "活动能力：" || text == "移动能力：" || text == "营养：" || text == "摩擦力：") {
            $(this).find('td').eq(1).find(":radio").each(function (i) {
                var label = $(this).parent();
                labelTexts = $(this).attr("hdnoption").split('☆');
                label.children().eq(1).text(labelTexts[0]);

                if ($(this).is(":checked")) {
                    value += parseInt(labelTexts[2]);
                }
            });
        }
    });
    if (braden != null) {
        if (value == 0) {
            braden.val("");
        }
        else {
            braden.val(value);
        }
        braden.attr("readonly", true);
    }
}

function initYcFsbw() {
    var jsonObj = [];
    if (eventID > 0) {
        $.ajax({
            url: "/AdverseEvent/EditAdverseEvent/GetAdverseEventYaChuangFsbwList?ram" + Math.random(),
            type: "post",
            async: false,
            data: { eventID: eventID },
            success: function (r) {
                jsonObj = $.parseJSON(r);
            }
        });
    }
    else {
        return;
    }
    $("#insertMode").nextAll().each(function () {
        var text = $(this).find('td').eq(0).text();
        if (text == "发生部位：") {
            var trId = "";
            $("[id^=fsbw_]").remove();
            for (var i = 0; i < jsonObj.length; i++) {
                $(this).find('input[type="checkbox"]').each(function () {
                    if ($(this).parent().text() == jsonObj[i].Name) {
                        if (i == 0 || (i > 0 && jsonObj[i].Name != jsonObj[i - 1].Name)) {
                            var tr = setYcFsbw($(this));
                            tr.find("#name").text(jsonObj[i].Name);
                            tr.find("#remarks").val(jsonObj[i].Remarks);
                            tr.find("#ycLevel").val(jsonObj[i].YcLevel);
                            tr.find("#position").val(jsonObj[i].Position);
                            tr.find("#startRange").val(jsonObj[i].StartRange);
                            tr.find("#endRange").val(jsonObj[i].EndRange);
                            tr.find("#seepage").val(jsonObj[i].Seepage);
                            tr.find("#peculiarSmell").val(jsonObj[i].PeculiarSmell);
                            trId = tr.attr("id");
                        }
                        else {
                            var tr = addTr(trId);
                            tr.find("#name").text(jsonObj[i].Name);
                            tr.find("#remarks").val(jsonObj[i].Remarks);
                            tr.find("#ycLevel").val(jsonObj[i].YcLevel);
                            tr.find("#position").val(jsonObj[i].Position);
                            tr.find("#startRange").val(jsonObj[i].StartRange);
                            tr.find("#endRange").val(jsonObj[i].EndRange);
                            tr.find("#seepage").val(jsonObj[i].Seepage);
                            tr.find("#peculiarSmell").val(jsonObj[i].PeculiarSmell);
                            trId = tr.attr("id");
                        }
                    }
                });
            }
        }
    });
}

function setYcFsbw(obj) {
    var trlist = $("[id^=fsbw_" + obj.parent().text() + "]");
    if (obj.is(":checked")) {
        if ($("#tbFsbw").length == 0) {
            obj.parent().parent().parent().append("<div style=\"margin: 10px 0px; width:95%;border:0px solid red;clear:both;\"><table id=\"tbFsbw\"></table></div>");
        }

        var trId = "fsbw_" + obj.parent().text() + "_" + Math.floor(Math.random().toFixed(5) * 10000);

        var temp = "<tr style=\"line-height: 35px;\">" +
                      "<td style=\"background-color: #fff;width: 100px; text-align: right; vertical-align: text-top;\"><font id=\"name\"></font>&nbsp;<input type=\"text\" id=\"position\" class=\"l-text\" maxlength=\"10\" style=\"width: 30px;\"/></td>" +
                      "<td style=\"background-color: #fff;\">" +
                      "<div style=\"float:left;margin-left:5px;\">" +
                          "<select id=\"ycLevel\">" +
                              "<option>压疮Ⅰ期</option>" +
                              "<option>压疮Ⅱ期</option>" +
                              "<option>压疮Ⅲ期</option>" +
                              "<option>压疮Ⅳ期</option>" +
                              "<option>压疮不可分期</option>" +
                              "<option>压疮深部组织损伤</option>" +
                          "</select>" +
                      "</div>" +
                      "<div style=\"float:left;margin-left:5px;\">" +
                          "范围：<input type=\"text\" id=\"startRange\" style=\"width:30px\" class=\"l-text\" maxlength=\"10\"/>cm × <input type=\"text\" id=\"endRange\" style=\"width:30px\" class=\"l-text\" maxlength=\"10\"/>cm" +
                      "</div>" +
                      "<div style=\"float:left;margin-left:5px;\">" +
                          "皮肤/创面描述：<input type=\"text\" id=\"remarks\" style=\"width:140px;\" class=\"l-text\" maxlength=\"10\"/>" +
                      "</div>" +
                      "<div style=\"float:left;margin-left:5px;\">" +
                          "渗液：<select id=\"seepage\"><option>无</option><option>有</option></select>" +
                      "</div>" +
                      "<div style=\"float:left;margin-left:5px;\">" +
                          "异味：<select id=\"peculiarSmell\"><option>无</option><option>有</option></select>" +
                      "</div>" +
                      "</td>" +
                      "<td style=\"background-color: #fff;width: 40px; vertical-align: text-top;padding-left:5px;\">" +
                          "<img id=\"addImg\" src=\"../../Content/images/icon/11.png\" style=\"width:15px; height:15px;\" onclick=\"addTr('" + trId + "')\" />" +
                      "</td>" +
                  "</tr>";

        var tr = $(temp);
        tr.attr('id', trId);
        tr.find("#name").text(obj.parent().text());
        $("#tbFsbw").append(tr);
        position();
        return tr;
    }
    else {
        trlist.remove();
        position();
    }
}

function addTr(id) {
    var oldTr = $("#" + id);
    var tr = oldTr.clone();
    var trId = "fsbw_" + id.split('_')[1] + "_" + Math.floor(Math.random().toFixed(5) * 10000);
    tr.attr("id", trId);
    tr.find("#remarks").val("");
    var td = tr.find("#addImg").parent();
    oldTr.find("#addImg").remove();
    td.html('');
    td.append($('<img id="delImg" src="../../Content/images/icon/12.png" style="width:15px; height:15px;" onclick="delTr(this,\'' + trId + '\');" />'));
    td.append($('<img id="addImg" src="../../Content/images/icon/11.png" style="width:15px; height:15px;" onclick="addTr(\'' + trId + '\')" />'));
    oldTr.after(tr);
    position();
    return tr;
}

function delTr(obj, id) {
    $(obj).parent().parent().remove();
    var str = id.split('_');
    if ($("[id^=" + str[0] + "_" + str[1] + "]").find("#addImg").length == 0) {
        var tr = $("[id^=" + str[0] + "_" + str[1] + "]:last");
        tr.find("td:last").append($('<img id="addImg" src="../../Content/images/icon/11.png" style="width:15px; height:15px;" onclick="addTr(\'' + tr.attr("id") + '\')" />'));
    }
    position();
}

function tableRowspan(_w_table_id, _w_table_colnum) {
    _w_table_firsttd = "";
    _w_table_currenttd = "";
    _w_table_SpanNum = 0;
    _w_table_Obj = $(_w_table_id + " tr td:nth-child(" + _w_table_colnum + ")");
    _w_table_Obj.each(function (i) {
        if (i == 0) {
            _w_table_firsttd = $(this);
            _w_table_SpanNum = 1;
        } else {
            _w_table_currenttd = $(this);
            if (_w_table_firsttd.text() == _w_table_currenttd.text() && _w_table_firsttd.find('font').eq(0).val() == _w_table_currenttd.find('font').eq(0).val()) {
                _w_table_SpanNum++
                _w_table_currenttd.hide();
                _w_table_firsttd.attr("rowSpan", _w_table_SpanNum);
            } else {
                _w_table_firsttd = $(this);
                _w_table_SpanNum = 1;
            }
        }
    });
}

function save(status, isReview) {
    var EventTypeID = $("#hdnEventTypeID").val();
    var EventTypeName = $("#eventTypeID").ligerComboBox().getText();
    var AreaID = $("#hdnAreaID").val();
    var AreaName = $("#areaID").ligerComboBox().getText();
    var PatientID = $("#hdnPatientID").val();
    var PatientName = $("#patientID").ligerComboBox().getText().split(' ')[1];
    var PatientSex = $("#txtPatientSex").val();
    var PatientAge = $("#txtPatientAge").val();
    var PatientAgeMonth = $("#txtPatientAgeMonth").val();
    var PatientAgeWeek = $("#txtPatientAgeWeek").val();
    var PatientAgeDay = $("#txtPatientAgeDay").val();
    var PatientAgeStr = $("#txtPatientAgeStr").val();
    if ($("#divAge").is(":visible")) {
        PatientAgeStr = "";
    }
    else {
        var PatientAge = "";
        var PatientAgeMonth = "";
        var PatientAgeWeek = "";
        var PatientAgeDay = "";
    }
    var PatientInTime = $("#txtPatientInTime").val();
    var IsTransfer = $('input:radio[name="isTransfer"]:checked').val();
    var TransferTime = "";
    var TransferDepartCode = "";
    var TransferDepartName = "";
    if (IsTransfer == 1) {
        TransferTime = $("#txtTransferTime").val();
        TransferDepartCode = $("#hdnTransferDepartCode").val();
        TransferDepartName = $("#transferDepartCode").ligerComboBox().getText();
    }
    var OccurrTime = $("#txtOccurrTime").val();
    var PatientNursingGrade = $("#hdnPatientNursingGrade").val();
    var PatientIsEscort = $('input:radio[name="patientIsEscort"]:checked').val();
    var PatientEscortValue = "";
    if (PatientIsEscort == 1) {
        var arr = new Array();
        $('[id^="patientIsEscort2_"]:checked').each(function (i) {
            arr[i] = $(this).val();
        });
        PatientEscortValue = arr.join("#");
    }
    var PatientDiagnosis = $("#txtPatientDiagnosis").val();
    var NurseWorkTimes = $("#txtWorkStartTime").val() + '~' + $("#txtWorkEndTime").val();
    var EventGrade = $('input:radio[name="eventGrade"]:checked').val();
    var EventGradeSubLevel = $('input:radio[name="eventGradeSubLevel"]:checked').val();
    var EventCourse = $("#txtEventCourse").val();
    var Measures = $("#txtMeasures").val();
    var Evaluation = $("#txtEvaluation").val();
    var YuHou = $("#txtYuHou").val();
    var ZhuanGui = $("#txtZhuanGui").val();
    var IsOutpatient = $('input:radio[name="isOutpatient"]:checked').val();
    var OutpatientTime = "";
    var OutpatientId = "";
    if (IsOutpatient == 1) {
        PatientName = $("#txtPatientName").val();
        OutpatientTime = $("#txtOutpatientTime").val();
        OutpatientId = $("#txtOutpatientId").val();
    }
    if (IsEmpty(PatientName)) {
        $.ligerDialog.error("患者不能为空");
        return;
    }

    var ModeList = [];
    for (var i = 0; i < modeJsonObj.length; i++) {
        modeJsonObj[i].Value = "";
        if (modeJsonObj[i].InputType == 0 || modeJsonObj[i].InputType == 1) {
            $("[id^=mode_" + modeJsonObj[i].ModeID + "_]").each(function () {
                modeJsonObj[i].Value += "#" + ($(this).is(':checked') ? "1" : "0");

                if ($(this).is(':checked') && $(this).attr("inputType") != undefined) {
                    if ($(this).attr("inputType") == 0 || $(this).attr("inputType") == 1) {
                        if ($("[id^=details_" + $(this).attr("id") + "_]").length > 0) {
                            if ($(this).attr("inputType") == 0) {
                                modeJsonObj[i].Value += "$0%0*";
                            }
                            else {
                                modeJsonObj[i].Value += "$0%1*";
                            }
                            $("[id^=details_" + $(this).attr("id") + "_]").each(function () {
                                modeJsonObj[i].Value += ($(this).is(':checked') ? "1" : "0") + "@";
                            });
                            modeJsonObj[i].Value = modeJsonObj[i].Value.substring(0, modeJsonObj[i].Value.length - 1);
                        }
                    }
                    else {
                        if ($(this).attr("inputType") == 2) {
                            modeJsonObj[i].Value += "$0%2*";

                        }
                        if ($(this).attr("inputType") == 3) {
                            modeJsonObj[i].Value += "$0%3*";
                        }

                        modeJsonObj[i].Value += $("#details_" + $(this).attr("id")).val();
                    }
                }
            });
            modeJsonObj[i].Value = modeJsonObj[i].Value.substring(1, modeJsonObj[i].Value.length);
            if (modeJsonObj[i].Value.indexOf("1") > -1) {
                ModeList.push(modeJsonObj[i]);
            }
        }
        else {
            modeJsonObj[i].Value = $("#mode_" + modeJsonObj[i].ModeID).val();
            if (modeJsonObj[i].Value != "") {
                ModeList.push(modeJsonObj[i]);
            }
        }
    }

    var ReasonList = [];
    $("#reasonList").find('input[type="checkbox"]:checked').each(function (i, eleDom) {
        if ($(this).attr("reason") == "其他" || $(this).attr("reason") == "其它") {
            var Reason = { ID: $(this).val(), OtherReason: $(this).parent().next().val() };
            ReasonList.push(Reason);
        }
        else {
            var Reason = { ID: $(this).val() };
            ReasonList.push(Reason);
        }
    });

    var NurseList = [];
    $("[id^=nurseItem_]").each(function () {
        var NurseID = $(this).attr("id").replace("nurseItem_", "");
        var NurseName = $("#nurseName_" + NurseID).text();
        var NurseAge = $("#nurseAge_" + NurseID).val();
        var NurseRank = $("#nurseRank_" + NurseID).val();
        var NurseWorkAge = $("#nurseWorkAge_" + NurseID).val();
        var NurseDepartAge = $("#nurseDepartAge_" + NurseID).val();
        var Nurse = { NurseID: NurseID, NurseName: NurseName, NurseAge: NurseAge, NurseRank: NurseRank, NurseWorkAge: NurseWorkAge, NurseDepartAge: NurseDepartAge };
        NurseList.push(Nurse);
    });
    if (NurseList.length == 0) {
        $.ligerDialog.error("请选择当事人");
        return;
    }

    var YaChuangFsbwList = [];
    $("[id^=fsbw_]").each(function () {
        var Name = $(this).find("#name").text();
        var YcLevel = $(this).find("#ycLevel").val();
        var Remarks = $(this).find("#remarks").val();
        var Position = $(this).find("#position").val();
        var StartRange = $(this).find("#startRange").val();
        var EndRange = $(this).find("#endRange").val();
        var Seepage = $(this).find("#seepage").val();
        var PeculiarSmell = $(this).find("#peculiarSmell").val();
        var YaChuangFsbw = { Name: Name, YcLevel: YcLevel, Remarks: Remarks, Position: Position, StartRange: StartRange, EndRange: EndRange, Seepage: Seepage, PeculiarSmell: PeculiarSmell };
        YaChuangFsbwList.push(YaChuangFsbw);
    });

    var YcFanKui = null;
    if ($("#divYcFanKui").is(':visible')) {
        YcFanKui = $.parseJSON($("#hdnYcFanKuiJson").val());
    }
    else {
        YuHou = "";
        ZhuanGui = "";
    }

    var AdverseEvent = {
        ID: eventID,
        EventTypeID: EventTypeID,
        EventTypeName: EventTypeName,
        OccurrDepartID: AreaID,
        OccurrDepartName: AreaName,
        PatientID: PatientID,
        PatientName: PatientName,
        PatientSex: PatientSex,
        PatientAge: PatientAge,
        PatientAgeMonth: PatientAgeMonth,
        PatientAgeWeek: PatientAgeWeek,
        PatientAgeDay: PatientAgeDay,
        PatientAgeStr: PatientAgeStr,
        PatientInTime: PatientInTime,
        PatientBedNo: bedNo,
        PatientVisitID: visitID,
        IsTransfer: IsTransfer,
        TransferTime: TransferTime,
        TransferDepartCode: TransferDepartCode,
        TransferDepartName: TransferDepartName,
        OccurrTime: OccurrTime,
        PatientNursingGrade: PatientNursingGrade,
        PatientIsEscort: PatientIsEscort,
        PatientEscortValue: PatientEscortValue,
        PatientDiagnosis: PatientDiagnosis,
        NurseWorkTimes: NurseWorkTimes,
        EventGrade: EventGrade,
        EventGradeSubLevel: EventGradeSubLevel,
        EventCourse: EventCourse,
        Measures: Measures,
        Evaluation: Evaluation,
        YuHou: YuHou,
        ZhuanGui: ZhuanGui,
        IsOutpatient: IsOutpatient,
        OutpatientTime: OutpatientTime,
        OutpatientId: OutpatientId,
        Status: status
    }
    var dataJson = {
        AdverseEvent: AdverseEvent,
        ModeList: ModeList,
        ReasonList: ReasonList,
        NurseList: NurseList,
        YaChuangFsbwList: YaChuangFsbwList,
        YcFanKui: YcFanKui,
        OldStatus: $("#hdnStatus").val()
    }

    if (isReview == 1) {
        return dataJson;
    }

    $.ajax({
        url: "/AdverseEvent/EditAdverseEvent/Save",
        type: 'post',
        data: JSON.stringify(dataJson),
        contentType: 'application/json;charset=utf-8',
        success: function (data) {
            var d = $.parseJSON(data);
            if (d.Result == 1) {
                eventID = d.Body;
                $("#hdnEventID").val(d.Body);
                if (status != $("#hdnStatus").val()) {
                    $.ligerDialog.success("上报成功");
                    setTimeout(function () { $("#btnBack").click(); }, 1000);
                }
                else {
                    $.ligerDialog.success("保存成功")
                }
                $("#btnReport").show();
                $("#btnYG").show();
            }
            else if (d.Result == 0) {
                $.ligerDialog.error(d.Body);
            }
            else {
                $.ligerDialog.error("程序错误");
            }
        },
        error: function () {
            $.ligerDialog.error("程序错误");
        }
    });
}

function ycFanKui() {
    $.ligerDialog.open({
        height: 330,
        width: 555,
        title: '编辑反馈信息',
        url: '/AdverseEvent/EditPressureSoreEvent/YcFanKui?eventId=' + eventID,
        showMax: false,
        showToggle: false,
        showMin: false,
        isResize: false,
        slide: false,
        data: { oldStatus: $("#hdnStatus").val() }
    });
}

function review(status) {
    $.ligerDialog.open({
        height: 300,
        width: 400,
        title: '请填写审核理由',
        url: '/AdverseEvent/AdverseEventReview/Review',
        showMax: false,
        showToggle: false,
        showMin: false,
        isResize: false,
        slide: false,
        data: { id: eventID, status: status, oldStatus: $("#hdnStatus").val(), yuHou: $("#txtYuHou").val(), zhuanGui: $("#txtZhuanGui").val() },
        buttons: [{
            text: '回调函数', onclick: function (i, d) {
                $("#btnBack").click();
            }

        }]
    });
    $(".l-dialog-buttons").hide();
}

function bindTransferDepartment() {
    if (!IsEmpty($("#hdnTransferDepartCode").val())) return;
    $("#transferDepartCode").ligerComboBox({
        width: 120,
        cancelable: false,
        url: "/AdverseEvent/EditAdverseEvent/GetAllUnits?ram" + Math.random(),
        valueField: "DepartmentCode",
        textField: "DepartmentName",
        valueFieldID: "hdnTransferDepartCode",
        value: $("#transferDepartCode").val(),
        onSuccess: function (data) {
            if ($("#transferDepartCode").val() == "") {
                $("#transferDepartCode").ligerComboBox().setValue(data[0].DepartmentCode);
            }
        }

    });
}